/**
 * 
 */

var wxAppid = 'wx149183c6b0bdba3f';

function isWeiXin(){
    var ua = window.navigator.userAgent.toLowerCase();
    if(ua.match(/MicroMessenger/i) == 'micromessenger' || ua.match(/_SQ_/i) == '_sq_'){
        return true;
    }else{
        return false;
    }
}

function isWxLogin() {
	var wxInfo = $.cookie('wxInfo');
	if (!wxInfo) return false;
	return true;
}

function validSessionLogin() {
	var wxInfo = $.cookie('wxInfo');
	
	/*Ajax.get({
		url: basePath + '/wx/validLogin' ,
		data:{
			openId:wxInfo.openid
		},
		callback: function 
	})*/
}

function wxLogin(){
	if ( !isWeiXin() ) return;
	if ( !isWxLogin() ) wxauthorization();
	var wxInfo = JSON.parse( $.cookie('wxInfo') );
	Ajax.get({
		url: basePath + '/wx/login',
		data:{
			openId:wxInfo.openid
		},
		callback: function ( data , count , respone ) {
			if (window.location.href != basePath + respone.msg) {
				window.location = basePath + respone.msg;
			}
		}
	})
}

function wxauthorization( reface ){
	
	if (!isWeiXin()) return;			// 非微信
	
	if (isWxLogin()&&!reface)return;	// 已授权
	
	if ( getUrlParam("code") ) {
		Ajax.query({
			url: basePath + '/wx/getWxInfo',
			data:{
				code: getUrlParam("code")
			},
			callback: function ( data , count , respone ) {
				setCookie("wxInfo" , JSON.stringify(data), 29);
			}
		})
	} else {
		var url = "http://" + window.location.host;
		window.location = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + wxAppid + "&redirect_uri=" + url + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
	}
}

$(function() {
	$(".header").load(basePath + "/i_header.html");				// 头部
	// $(".nav-table").load(basePath + "/i_shopNav.html");
	$(".tip").load(basePath + "/i_menu.html");						
	$(".white").load(basePath + "/i_search.html");					
	$(".footer").load(basePath + "/i_footer.html");		
	
	// $(".navCir").load(basePath + "/i_navCir.html");
	setTimeout(function () {
		renderCartNum();
		rederLoginInfo();
		wxauthorization();
		loadingend();
	} , 200)
});


function loadingend (){
	/*$('#loading').modal('close');*/
	$('body').show();
}


Date.prototype.Format = function(formatStr) {
	var str = formatStr || 'yyyy-MM-dd HH:mm:ss';
	var Week = [ '日', '一', '二', '三', '四', '五', '六' ];

	str = str.replace(/yyyy|YYYY/, this.getFullYear());
	str = str.replace(/yy|YY/, (this.getYear() % 100) > 9 ? (this.getYear() % 100).toString() : '0' + (this.getYear() % 100));

	str = str.replace(/MM/, (this.getMonth() + 1) > 9 ? ((this.getMonth() + 1) + '') : '0' + (this.getMonth() + 1));
	str = str.replace(/M/g, (this.getMonth() + 1));

	str = str.replace(/w|W/g, Week[this.getDay()]);

	str = str.replace(/dd|DD/, this.getDate() > 9 ? this.getDate().toString() : '0' + this.getDate());
	str = str.replace(/d|D/g, this.getDate());

	str = str.replace(/hh|HH/, this.getHours() > 9 ? this.getHours().toString() : '0' + this.getHours());
	str = str.replace(/h|H/g, this.getHours());
	str = str.replace(/mm/, this.getMinutes() > 9 ? this.getMinutes().toString() : '0' + this.getMinutes());
	str = str.replace(/m/g, this.getMinutes());

	str = str.replace(/ss|SS/, this.getSeconds() > 9 ? this.getSeconds().toString() : '0' + this.getSeconds());
	str = str.replace(/s|S/g, this.getSeconds());

	return str;
}


function getMoney(value) {
	if (value == null || value == 0 || value == undefined || value == "&#160;") { //如果是空
		return '0.00';
	} else {
		value = value / 100;
		var result = (value.toString()).indexOf(".");
		if (result != -1) {
			if (value.toString().substring(result, value.length).length >= 3) { //如果小数点到末尾的长度大于等于3
				if (typeof value == 'string') { //因为toFixed只对Number起作用，所以，如果当前的值是string类型，则转为number
					return parseInt(value).toFixed(2) + '';
				}
				return value.toFixed(2) + ''; //截取小数点后两位
			} else {
				return value + '0';
			}
			return value + '';
		} else {
			return value + '.00';
		}
		return value + '';
	}
}


function message(msg, type , callback) {
	if (isWeiXin()) {
		alert(msg);
		return;
	}
	
//	$('#alert-title').html('提示');
	$('#alert-msg').html(msg);
	
	$('#alert').modal({
		onCancel:callback
	});
}


function removeShopcart(id ) {
	var shopcart = $.cookie('shopcart');
	if (!shopcart) return;
	shopcart = JSON.parse(shopcart);
	var arr = [];
	for (var i in shopcart) {
		var s = shopcart[i];
		if (s.id != id) {
			arr.push(s);
		} 
	}
	if (arr.length == 0) {
		$.removeCookie('shopcart');
	} else {
		setCookie('shopcart', JSON.stringify(arr));
	}
	renderCartNum();
}

/*
function addShopcart(id, num) {
	var shopcart = $.cookie('shopcart');
	if (shopcart) {
		shopcart = JSON.parse($.cookie('shopcart'));
	} else {
		shopcart = [];
	}
	
	if (shopcart.length >= 20) {
		message('当前购物车已添加20件商品，请结算后再添加');
		return;
	}
	// 判断购物车中是否已存在
	for (var i in shopcart) {
		var s = shopcart[i];
		if (s.id == vm.id) {
			message('购物车中已存在当前商品');
			return;
		}
	}
	shopcart.push({
		id : vm.id,
		num : $('#text_box').val()
	})
	setCookie('shopcart', JSON.stringify(shopcart));
	message('添加成功', 'success');
	renderCartNum();
}
*/
function addShopcartById(id, num) {
	var shopcart = $.cookie('shopcart');
	if (shopcart) {
		shopcart = JSON.parse($.cookie('shopcart'));
	} else {
		shopcart = [];
	}

	if (shopcart.length >= 20) {
		message('当前购物车已添加20件商品，请结算后再添加');
		return;
	}
	// 判断购物车中是否已存在
	for (var i in shopcart) {
		var s = shopcart[i];
		if (s.id == id) {
			message('购物车中已存在当前商品');
			return;
		}
	}
	shopcart.push({
		id : id,
		num : (num || $('#text_box').val())
	})
	setCookie('shopcart', JSON.stringify(shopcart));
	message('添加成功', 'success');
	renderCartNum();
}

function rederLoginInfo( ) {
	Ajax.get({
		url: basePath + '/member/loginInfo' , 
		callback: function (data ) {
			if (data && data != 'null' && data.memberInfo) {
				$('.message-l .topMessage .menu-hd').html('欢迎登陆，' + data.memberInfo.name + ' <a href="javascript:logout()" style="color:#999;">【退出】</a> ');
			}
		}
	})
}

function logout() {
	Ajax.get({
		url: basePath + '/member/logout',
		callback: function () {
			message('已退出登录');
			window.location.reload();
		}
	})
}

function renderCartNum( ) {
	var shopcart = $.cookie('shopcart');
	if (shopcart) {
		shopcart = JSON.parse($.cookie('shopcart'));
	} else {
		shopcart = [];
	}
	$('#J_MiniCartNum').html(shopcart.length);
	$('#shopcart_nav_num').html(shopcart.length);
	
	// renderHeader
}

function setCookie(key, value , expires) {
	expires = expires || 365;
	$.cookie(key, value, {
		expires : expires,
		path : '/'
	}) ;
}

function validLogin(callback) {
}

function addCollection(id) {
	Ajax.add({
		url : basePath + '/person/addCollection',
		data : {
			id : id
		}
	})
}


function loginDialog() {
	// 微信端打开绑定手机界面
	if (isWeiXin()) {
		window.location = '/bindphone';
	}
	
	$('#my-login-alert').modal({
		closeOnConfirm : true
	});

}

function openYishengqr ( ) {
	$('#yishengqr-dialog').modal({
		closeOnConfirm : true
	});
	
}

function openMemberRule ( ) {
	$('#member-rule').modal({
		closeOnConfirm : true
	});
	
}

function checkPhone(phone) {
	if (!(/^1[345789]\d{9}$/.test(phone))) {
		message("手机号码有误，请重填");
		return false;
	}
	return true;
}


function toBarSearch() {
	window.location = basePath + '/search?title=' + decToHex($('#searchInput').val())
}

function getQueryString(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	var r = window.location.search.substr(1).match(reg);
	if (r != null) return unescape(r[2]);
	return null;
}

var decToHex = function(str) {
	var res = [];
	for (var i = 0; i < str.length; i++)
		res[i] = ("00" + str.charCodeAt(i).toString(16)).slice(-4);
	return "\\u" + res.join("\\u");
}
var hexToDec = function(str) {
	str = str.replace(/\\/g, "%");
	return unescape(str);
}

function getUrlParam(variable) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i = 0; i < vars.length; i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
			return pair[1];
		}
	}
	return (false);
}


function goSearch( ) {
	window.location.href = basePath + '/search?title=' + $('#searchInput').val();
}

function getCarriageDesc( callback ) {
	Ajax.get( {
		url: basePath + '/product/carriageDesc' ,
		callback: function ( data ) {
			callback(data);
		}
	})
	
}
